package bosc.cn.service.impl;


import bosc.cn.controller.dto.RustSignReqDTO;
import bosc.cn.controller.dto.RustSignResDTO;
import bosc.cn.controller.entity.RustSignEntity;
import bosc.cn.excception.BusinessException;
import bosc.cn.service.RustSignService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @author tianshq
 * @date 2025/9/6 19:17
 * @description RustSignServiceImpl
 * curl -X POST http://localhost:18080/sign \
 * -H "Content-Type: application/json" \
 * -d '{
 * "local_id": 0,
 * "peer_id": 1,
 * "message": "test",
 * "local_ip": "ip1",
 * "peer_ip": "ip2",
 * "local_port": 8080,
 * "peer_port": 8080
 * }'
 * <p>
 * curl -X POST http://localhost:18080/verify \
 * -H "Content-Type: application/json" \
 * -d '{
 * "r": "签名结果r",
 * "s": "签名结果s",
 * "aead": "test"
 * }'
 */
@Service("rustSignService")
@Slf4j
public class RustSignServiceImpl implements RustSignService {


    @Value("${rust.sign.url}")
    private String rustSignUrl;

    @Autowired
    @Qualifier("unSSLRestTemplate")
    private RestTemplate restTemplate;

    @Override
    public RustSignResDTO sign(RustSignReqDTO rustSign) {
        try {
            log.info("rust签名入参: {}", JSON.toJSONString(rustSign));

            //转成下划线格式请求rust
            RustSignEntity rustSignEntity = new RustSignEntity();
            rustSignEntity.setLocal_id(rustSign.getLocalId());
            rustSignEntity.setPeer_id(rustSign.getPeerId());
            rustSignEntity.setMessage(rustSign.getMessage());
            rustSignEntity.setLocal_ip(rustSign.getLocalIp());
            rustSignEntity.setPeer_ip(rustSign.getPeerIp());
            rustSignEntity.setLocal_port(rustSign.getLocalPort());
            rustSignEntity.setPeer_port(rustSign.getPeerPort());

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);

            HttpEntity<Object> entity = new HttpEntity<>(rustSignEntity, headers);

            // 从配置文件读取 rustSignUrl，若未配置默认使用本地地址
            log.info("Rust签名服务调用路径: {},调用请求体{}", rustSignUrl,entity);

            // 开始计时
            long start = System.currentTimeMillis();

            ResponseEntity<String> response = restTemplate.exchange(
                    rustSignUrl,
                    HttpMethod.POST,
                    entity,
                    String.class
            );
            // 结束计时
            long end = System.currentTimeMillis();
            log.info("Rust签名服务响应耗时: {} ms", (end - start));

            String body = response.getBody();
            log.info("rust签名返回: {}", body);

            if ("200".equals(String.valueOf(response.getStatusCodeValue()))) {
                return JSON.parseObject(body, RustSignResDTO.class);
            } else {
                throw new BusinessException("Rust签名服务调用失败，状态码：" + response.getStatusCodeValue());
            }
        } catch (Exception e) {
            log.error("Rust签名服务调用异常: {}", e.getMessage(), e);
            throw new BusinessException("Rust签名服务调用异常：" + e.getMessage());
        }
    }


}
